import axios from 'axios';
import { Toast } from 'vant';
import NProgress from 'nprogress';//进度条
import code from './code';    //错误码

axios.defaults.timeout = 5000;

let loading;

// http request 拦截器
axios.interceptors.request.use(config => {
  NProgress.start();
  loading = Toast.loading({
    mask: true,
    message: '加载中...'
  });
  return config;
},error => {
  NProgress.done();
  loading.clear();
  Toast('请求失败');
  return Promise.reject(error);
});

// http response 拦截器
axios.interceptors.response.use(res => {
  NProgress.done();
  loading.clear();
  return res;
  //let status = res.status;
  /*if(status === 200){
    const { code: requestCode, msg } = res.data;
    if (requestCode === code.SUCCESS){
      return res;
    }else {
      switch (requestCode) {
        case code.UN_LOGIN:
          //未登录
          break;
        case code.BIND_PHONE:
          //未登录
          break;
        case code.MESSAGE:
          Toast(msg);
          break;
        case code.LOGIN_EXPIRE:
          Toast(msg);
          break;
        default:
      }
    }
  }*/
},error => {
  NProgress.done();
  loading.clear();
  const status = error.response.status;
  if(error && error.response){
    switch (status) {
      case 400:
        Toast('请求错误');
        break;
      case 401:
        Toast('未授权，请登录');
        break;
      case 403:
        Toast('拒绝访问');
        break;
      case 404:
        Toast(`请求地址出错: ${error.response.config.url}`);
        break;
      case 408:
        Toast('请求超时');
        break
      case 500:
        Toast('服务器内部错误');
        break;
      case 501:
        Toast('服务未实现');
        break;
      case 502:
        Toast('网关错误');
        break;
      case 503:
        Toast('服务不可用');
        break;
      case 504:
        Toast('网关超时');
        break;
      case 505:
        Toast('HTTP版本不受支持');
        break;
      default:
    }
  }
  return Promise.reject(error);
})

export default axios;
